//
//  DetailViewController.swift
//  OverseasOnlineShopping
//
//  Created by 唐先才 on 16/3/8.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate {
    
    var tableView = UITableView(frame: CGRect(x: 0, y: 64, width: WIDTH, height: HEIGHT - 44 - 64), style: .Grouped)
    var dataArray: NSMutableArray = []
    var commentDataArray: NSMutableArray = []
    var likeDataArray: NSMutableArray = []
    var parameters: NSDictionary?
    var pic_url: String?
    var headView = UIView()
    var headImage = UIImageView()
    var webHeight: CGFloat?
    var web = UIWebView()
    var modelWeb: TxcModel?
    var goodsID: String?
    var waitView = WaitLoadView(frame: UIScreen.mainScreen().bounds)
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
        self.navigationController?.navigationBarHidden = true
        self.title = "商品详情"
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabBarController?.tabBar.hidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        createNavBar()
        createToolBar()
        createData()
        createUI()
        waitView.frame = UIScreen.mainScreen().bounds
        view.addSubview(waitView)
    }

    func createNavBar() {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: 64))
        view.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(view)
        let leftBtn = UIButton(type: .System)
        leftBtn.frame = CGRect(x: 0, y: 20, width: 40, height: 40)
//        leftBtn.setImage(UIImage(named: "back"), forState: .Normal)
        leftBtn.setBackgroundImage(UIImage(named: "back"), forState: .Normal)
        leftBtn.addTarget(self, action: "goBackToRecommend", forControlEvents: .TouchUpInside)
        view.addSubview(leftBtn)
        let titleLab = UILabel(frame: CGRect(x: WIDTH / 2 - 40, y: 30, width: 80, height: 30))
        titleLab.textColor = UIColor.blackColor()
        titleLab.text = "商品详情"
        titleLab.textAlignment = NSTextAlignment.Center
        titleLab.font = UIFont.boldSystemFontOfSize(18)
        view.addSubview(titleLab)
        
    }
    
    func goBackToRecommend() {
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    func createToolBar() {
        
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: HEIGHT - 44, width: WIDTH, height: 44))
        toolBar.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(toolBar)
        
        let imgArray = ["praise_gray", "collect_gray", "cart_gray"]
        let sImgArray = ["praise_red", "collect_red", "cart_red"]
        for index in 0..<3 {
            let button = UIButton(type: .Custom)
            button.frame = CGRect(x: CGFloat(index) * WIDTH / 4.0, y: 0, width: WIDTH / 4.0, height: 20)
            button.setImage(UIImage(named: imgArray[index]), forState: .Normal)
            button.setImage(UIImage(named: sImgArray[index]), forState: .Selected)
            button.tag = 1000 + index
            button.addTarget(self, action: "clickAction:", forControlEvents: .TouchUpInside)
            let label = UILabel(frame: CGRect(x: CGFloat(index) * WIDTH / 4.0, y: 20, width: WIDTH / 4.0, height: 20))
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(11)
            if index == 0 {
                label.text = "赞"
            } else if index == 1 {
                label.text = "收藏"
            } else {
                label.text = "购物车"
            }
            toolBar.addSubview(button)
            toolBar.addSubview(label)
        }
        let goBtn = UIButton(type: .Custom)
        goBtn.frame = CGRect(x: CGFloat(3) * WIDTH / 4, y: 0, width: WIDTH / 4, height: 44)
        goBtn.backgroundColor = UIColor.orangeColor()
        goBtn.setTitle("立即购买", forState: .Normal)
        goBtn.addTarget(self, action: "goBuy", forControlEvents: .TouchUpInside)
        toolBar.addSubview(goBtn)
    }

    
    func clickAction(button: UIButton) {
        
    }
    
    func goBuy(button: UIButton) {
        
    }

    func createData() {
        let manager = AFHTTPRequestOperationManager()
        //第一部分
        manager.POST(scroller_detail, parameters: self.parameters, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict in array {
                let model = TxcModel(dict: dict)
                self.dataArray.addObject(model)
                
            }
            self.createWeb()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                SVProgressHUD.showErrorWithStatus(AppNetErrorTips)
        }
        //第三部分
        guard let str = self.goodsID else {
            return
        }
        let parameters3 = ["clientLanType": "1",
            "infoID": str,
            "pageIndex": "1",
            "pageSize": "2"
        ]
        manager.POST(collectComment_url, parameters: parameters3, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                print("评论解包失败")
                return
            }
            for dict3 in array {
                let model = TxcModel(dict: dict3)
                self.commentDataArray.addObject(model)
            }
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                print("_____\(error)")
                SVProgressHUD.showErrorWithStatus(AppNetErrorTips)
        }
        
        //第四部分
        let parameters4 = ["catUrl": "",
            "homeShow": "1",
            "infoID": str,
            "infoType": "5",
            "keyWord": "",
            "mayLikeCatCount": "4"
        ]
        manager.POST(collectLike_url, parameters: parameters4, success: { (operation: AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                print("猜你喜欢解包失败")
                return
            }
            for dict4 in array {
                let model = TxcModel(dict: dict4)
                self.likeDataArray.addObject(model)
            }
            self.tableView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
        }
    }
    
    func createUI() {
        //        tableView.backgroundColor = UIColor.whiteColor()
        //        tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)
        
        headView.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 350)
//        headView.layer.contents = UIImage(named: "gray")?.CGImage
        headView.backgroundColor = UIColor.whiteColor()
        headImage.frame = headView.frame
        headImage.contentMode = UIViewContentMode.ScaleAspectFit
        headImage.sd_setImageWithURL(NSURL(string: self.pic_url!))
        headView.addSubview(headImage)
        tableView.tableHeaderView = headView
        let nib1 = UINib(nibName: "DetailCellOne", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib1, forCellReuseIdentifier: "detailCellOne")
        let nib3 = UINib(nibName: "DetailCellThree", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib3, forCellReuseIdentifier: "detailCellThree")
        let nib4 = UINib(nibName: "DetailCellFour", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib4, forCellReuseIdentifier: "detailCellFour")
    }
    
    func createWeb() {
        guard let modelWeb = self.dataArray[0] as? TxcModel else {
            print("model传值失败")
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 100)
        web.delegate = self
        web.scrollView.userInteractionEnabled = true
        web.scrollView.scrollEnabled = false
        guard let content = modelWeb.InfoContent else {
            return
        }
        //        let string = "<head><style>img{max-width:320px !important;}</style></head>" + content
        let string = "<head><style>img{max-width:300px !important;}</style></head>" + content
        web.loadHTMLString(string, baseURL: nil)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else if section == 1 {
            return 1
        } else if section == 2 {
            if self.commentDataArray.count > 0 {
                return self.commentDataArray.count + 1
            }
        }
        return self.likeDataArray.count + 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let detailCellOne = DetailCellOne.detailCellOneWith(tableView, dataArray: self.dataArray, indexPath: indexPath)
            return detailCellOne
        } else if indexPath.section == 1 {
            var cell1 = tableView.dequeueReusableCellWithIdentifier("cell1")
            if (cell1 == nil) {
                cell1 = UITableViewCell(style: .Default, reuseIdentifier: "cell1")
            }
            guard let webCell = cell1 else {
                print("cell1 解包失败")
                return UITableViewCell()
            }
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.row] as? TxcModel {
                    modelWeb = model
                    webCell.contentView.addSubview(web)
                }
            }
            return webCell
        } else if indexPath.section == 2 {
            let detailCellThree = DetailCellThree.detailCellThreeWith(tableView, dataArray: self.commentDataArray, indexPath: indexPath)
            return detailCellThree
        } else if indexPath.section == 3 {
            let detailCellFour = DetailCellFour.detailCellFourWith(tableView, dataArray: self.likeDataArray, indexPath: indexPath)
            return detailCellFour
        }
        return UITableViewCell()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        let str = webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")
        webHeight = CGFloat((str! as NSString).floatValue)
        //        print("++++\(webHeight)+++++")
        guard let webH = webHeight else {
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: webH)
        tableView.reloadData()
        waitView.removeFromSuperview()
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 100
        } else if indexPath.section == 1 {
            return web.frame.size.height + 20
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                return 30
            }
            if self.commentDataArray.count > 0 {
                guard let model = self.commentDataArray[indexPath.row - 1] as? TxcModel else {
                    return 0
                }
                if model.ReviewContent == nil {
                    return 40
                }
                return 80
            }
        } else if indexPath.section == 3 {
            if indexPath.row == 0 {
                return 30
            }
            return 100
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 1
        } else if section == 2{
            return 10
        } else if section == 3 {
            return 10
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var offset = tableView.contentOffset.y
        if offset > 0 {
            offset = 0
        }
        headImage.frame = CGRect(x: 0 + offset / 2, y: offset, width: WIDTH - offset * 0.8, height: 350 - offset)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}
